const sqlite3 = require('sqlite3').verbose();

const DATABASE_PATH = 'D:\\文档\\工程文件\\MTalk-Project\\mtalk_desk\\src\\assets\\db\\mtalk-database.db';

function openDb() {
    return new sqlite3.Database(DATABASE_PATH, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err) => {
        if (err) {
            console.error('Error opening database:', err.message);
        }
    });
}

async function ws_selectDeviceList() {
    return new Promise((resolve, reject) => {
        const db = openDb();
        db.all(`SELECT * FROM system_ws`, [], (err, rows) => {
            if (err) {
                reject(err);
            } else {
                resolve(rows);
            }
            db.close();
        });
    });
}

async function ws_insertDevice(device) {
    return new Promise((resolve, reject) => {
        const db = openDb();
        db.run(`INSERT INTO system_ws (ws_id, name, ip, port, status) VALUES (?, ?, ?, ?, ?)`,
            [device.ws_id, device.name, device.ip, device.port, device.status],
            function(err) {
                if (err) {
                    reject(err);
                } else {
                    resolve(this.lastID);
                }
                db.close();
            });
    });
}

async function ws_updateDevice(device) {
    return new Promise((resolve, reject) => {
        const db = openDb();
        db.run(`UPDATE system_ws SET name = ?, ip = ?, port = ?, status = ? WHERE ws_id = ?`,
            [device.name, device.ip, device.port, device.status, device.ws_id],
            function(err) {
                if (err) {
                    reject(err);
                } else {
                    resolve(this.changes);
                }
                db.close();
            });
    });
}

async function ws_deleteDevice(ws_id) {
    return new Promise((resolve, reject) => {
        const db = openDb();
        db.run(`DELETE FROM system_ws WHERE ws_id = ?`, [ws_id], function(err) {
            if (err) {
                reject(err);
            } else {
                resolve(this.changes);
            }
            db.close();
        });
    });
}

module.exports = {
    ws_selectDeviceList,
    ws_insertDevice,
    ws_updateDevice,
    ws_deleteDevice
};
